<template>
  <div class="config-wrapper systemConfig-wraaper">
    <!-- <div class="main-hd">
      <h2>{{$t('m.xìtǒngpèizhì')}}</h2>
    </div>-->
    <div class="title">
      <div class="borderLeft"></div>
      <span>{{$t('m.basicConfig')}}</span>
    </div>
    <div class="content-wrap">
      <Table :columns="columns" :data="configData" :loading="configLoading" border/>
    </div>
    <Withdraw/>
    <div class="title">
      <div class="borderLeft"></div>
      <span>{{$t('m.payConfig')}}</span>
    </div>
    <div class="content-wrap">
      <Table :columns="payColumns" :data="payData" :loading="configLoading" border/>
    </div>
    <div class="content-wrap" style="margin-bottom: 30px;">
      <div style="display: flex; justify-content: flex-end;">
        <Button class="addUserBtn" type="primary" @click="addUserModal">
          <Icon type="md-add"/>
          {{$t('m.addAccount')}}
        </Button>
      </div>
      <Table :columns="companyBankColumns" :data="companyBankData" :loading="configLoading" border/>
    </div>
    <Modal v-model="adminModal" :title="$t('m.edV')" @on-ok="ok()" @on-cancel="cancel">
      <p>
        <span class="admin-label">{{$t('m.inV')}}:</span>
        <Input v-model="peizhi" style="margin: 10px 0"></Input>
        <span class="admin-label">{{$t('m.inPzsu')}}:</span>
        <Input v-model="remark" style="margin: 10px 0" disabled></Input>
      </p>
    </Modal>
    <Modal
      :loading="loading"
      :value="editModal"
      :title="$t('m.edit')"
      @on-ok="editCompanyBank('formValidate')"
      @on-cancel="editModal = false;"
    >
      <Form ref="formValidate" :model="companyBankItem" :rules="ruleValidate" :label-width="80">
        <FormItem :label="$t('m.lèixíng')" prop="wayNum">
          <Select v-model="companyBankItem.wayNum" :placeholder="$t('m.lèixíng')">
            <Option :value=0>{{$t('m.onlineAccount')}}</Option>
            <Option :value=1>{{$t('m.offlineAccount')}}</Option>
          </Select>
        </FormItem>
        <FormItem :label="$t('m.xingming')" prop="accountName">
          <Input v-model="companyBankItem.accountName" :placeholder="$t('m.xingming')"></Input>
        </FormItem>
        <FormItem :label="$t('m.kǎhào')" prop="accountNo">
          <Input v-model="companyBankItem.accountNo" :placeholder="$t('m.kǎhào')"></Input>
        </FormItem>
        <FormItem :label="$t('m.bankName')" prop="bankName">
          <Input v-model="companyBankItem.bankName" :placeholder="$t('m.bankName')"></Input>
        </FormItem>
        <FormItem :label="$t('m.branchBank')" prop="bankBranchName">
          <Input v-model="companyBankItem.bankBranchName" :placeholder="$t('m.branchBank')"></Input>
        </FormItem>
        <FormItem :label="$t('m.priority')" prop="sortNum">
          <InputNumber style="width: 100%;" :min="0" :precision="0" v-model="companyBankItem.sortNum" :placeholder="$t('m.priority')"></InputNumber>
        </FormItem>
        <FormItem :label="$t('m.status')" prop="status">
          <Select v-model="companyBankItem.status"  :value="1"  :placeholder="$t('m.status')">
            <Option :value=1>{{$t('m.enable')}}</Option>
            <Option :value=0>{{$t('m.disable')}}</Option>
          </Select>
        </FormItem>
        <FormItem :label="$t('m.bèizhù')" prop="remark">
          <Input
            v-model="companyBankItem.remark"
            type="textarea"
            :autosize="{minRows: 2,maxRows: 5}"
            :placeholder="$t('m.bèizhù')"
          ></Input>
        </FormItem>
      </Form>
    </Modal>
    <Modal
      v-model="delModal"
      :title="$t('m.delete')"
      @on-ok="deleteCompanyBank"
      @on-cancel="delModal = false;"
    >
      <p>{{$t('m.areyoudel')}}</p>
    </Modal>
  </div>
</template>

<script>
import Withdraw from "./withdraw";
import { setTimeout } from 'timers';

export default {
  name: "configManage",
  components: {
    Withdraw
  },
  data() {
    return {
      creationType:true,
      adminModal: false,
      loading: true,
      delModal: false,
      editModal: false,
      peizhi: "",
      remark: "",
      companyBankItem: {},
      row: {},
      ruleValidate: {
        wayNum: [
          {
            type: 'number',
            required: true,
            message: this.$t("m.selectType"),
            trigger: "change"
          }
        ],
        accountName: [
          {
            required: true,
            message: this.$t("m.pleaseName"),
            trigger: "blur"
          }
        ],
        accountNo: [
          {
            required: true,
            message: this.$t("m.pleaseCard"),
            trigger: "blur"
          }
        ],
        bankName: [
          {
            required: true,
            message: this.$t("m.pleaseBankName"),
            trigger: "blur"
          }
        ],
        sortNum: [
          {
            type: 'number',
            required: true,
            message: this.$t("m.pleasePriority"),
            trigger: "blur"
          }
        ],
        status: [
          {
            type: 'number',
            required: true,
            message: this.$t("m.qǐngxuǎnzézhuàngtài"),
            trigger: "change"
          }
        ]
      },
      configData: [],
      payData: [],
      companyBankData: [],
      payColumns: [
        {
          title: this.$t("m.category"),
          key: "payRemark",
          align: "center"
        },
        {
          title: this.$t("m.operate"),
          align: "center",
          render: (h, param) => {
            const {
              row: { payValue }
            } = param;

            return h("i-switch", {
              props: {
                value: payValue === "1" ? true : false
              },
              on: {
                "on-change": () => this.changePayStatus(param)
              }
            });
          }
        }
      ],
      companyBankColumns: [
        {
          title: this.$t("m.type"),
          key: "wayNum",
          align: "center",
          render: (h, param) => {
            const {
              row: { wayNum }
            } = param;
            const obj = {
              0: this.$t("m.onlineAccount"),
              1: this.$t("m.offlineAccount")
            };
            return h("div", obj[wayNum]);
          }
        },
        {
          title: this.$t("m.xingming"),
          key: "accountName",
          align: "center"
        },
        {
          title: this.$t("m.kǎhào"),
          key: "accountNo",
          align: "center"
        },
        {
          title: this.$t("m.bankName"),
          key: "bankName",
          align: "center"
        },
        {
          title: this.$t("m.priority"),
          key: "sortNum",
          align: "center"
        },
        {
          title: this.$t("m.status"),
          key: "status",
          align: "center",
          render: (h, param) => {
            const {
              row: { status }
            } = param;
            const obj = {
              0: this.$t("m.disable"),
              1: this.$t("m.enable"),
              2: this.$t("m.delete")
            };
            return h("div", obj[status]);
          }
        },
        {
          title: this.$t("m.bèizhù"),
          key: "remark",
          align: "center"
        },
        {
          title: this.$t("m.operate"),
          align: "center",
          width:200,
          render: (h, param) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "warning"
                  },
                  on: {
                    click: () => {
                      this.creationType = false;
                      this.editModal = true;
                      const row = Object.assign({}, param.row);
                      this.companyBankItem = row;
                      this.$refs['formValidate'].resetFields();
                    }
                  }
                },
                this.$t("m.edit")
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error"
                  },
                  style: {
                    marginLeft: "10px"
                  },
                  on: {
                    click: () => {
                      this.delModal = true;
                      this.row = param.row;
                    }
                  }
                },
                this.$t("m.delete")
              )
            ]);
          }
        }
      ],
      columns: [
        {
          title: this.$t("m.pzSu"),
          key: "remark",
          align: "center"
        },
        {
          title: this.$t("m.pzVal"),
          key: "value",
          align: "center"
        },
        {
          title: this.$t("m.operate"),
          align: "center",
          render: (h, param) => {
            const { row } = param;
            return h(
              "Button",
              {
                props: {
                  type: "warning",
                  size: "small"
                },
                style: {
                  marginBottom: "10px"
                },
                on: {
                  click: () => this.handleOpenEdit(row)
                }
              },
              this.$t("m.edPz")
            );
          }
        }
      ]
    };
  },
  created() {
    this.getConfigList();
    this.getCompanyBankcardList();
    this.getCompanyBankList();
  },
  methods: {
    //  新增帐号
    addUserModal() {
      this.editModal = true;
      this.companyBankItem = {sortNum:1,status:1};
      this.$refs['formValidate'].resetFields();
    },
    //  编辑配置
    handleOpenEdit(item) {
      this.adminModal = true;
      this.id = item.id;
      this.name = item.name;
      this.peizhi = item.value;
      this.remark = item.remark;
    },
    ok() {
      var _self = this;
      var id = _self.id;
      this.$http
        .post("/api/laocai/sys/config/update", {
          id: id,
          value: this.peizhi,
          remark: this.remark
        })
        .then(
          res => {
            if (res.body.code == 0) {
              this.$Message.success(res.body.message);
              $("#adminModal").modal("hide");
              this.getConfigList();
            } else {
              this.$Message.warning(res.body.message);
            }
          },
          error => {
            console.log(error);
          }
        );
    },
    cancel() {
      // this.$Message.info("Clicked cancel");
    },
    //  获取支付配置列表
    async getCompanyBankcardList() {
      const { body } = await this.$http.get("/api/laocai/sysPayConfig/list");

      if (body.code === 0) {
        this.payData = body.result || [];
      } else {
        this.payData = [];
      }
    },
    async changePayStatus(param) {
      const {
        row: { id, ctime, utime, payName, payRemark, payValue }
      } = param;
      const { body } = await this.$http.post("/api/laocai/sysPayConfig/info", {
        id,
        payName:payName,
        payValue: payValue == 1 ? 0 : 1
      });
      
      if (body.code === 0) {
        this.$Message.success(this.$t('m.errorCode' + body.code));
      } else {
        this.$Message.error(this.$t('m.errorCode' + body.code));
      }
      this.getCompanyBankcardList()
    },
    //  获取收款银行账户列表
    async getCompanyBankList() {
      const { body } = await this.$http.get(
        "/api/laocai/sysPayConfig/companyBankcard/list"
      );
      if (body.code === 0) {
        this.companyBankData = body.result || [];
      } else {
        this.companyBankData = [];
      }
    },
    editCompanyBank(name) {
      this.$refs[name].validate(async (valid) => {
        if (valid) {
          const {
            id,
            bankName,
            bankBranchName,
            accountNo,
            accountName,
            wayNum,
            sortNum,
            remark,
            status
          } = this.companyBankItem;

          if (this.creationType) {
            const response = await this.$http.get("/api/laocai/sysPayConfig/check/sortNum?sortNum=" + sortNum);
            if (!response.body.result) {
              this.loading = false;
              setTimeout(() => {
                this.loading = true;
              }, 0)
              return this.$Message.error(this.$t('m.cannotrepeat'));
            }
              
          }

          const params = {
            status,
            bankName,
            bankBranchName,
            accountNo,
            accountName,
            wayNum,
            remark,
            sortNum
          };

          if (id) {
            params.id = id;
          }

          const { body } = await this.$http.post(
            "/api/laocai/sysPayConfig/companyBankcard/info",
            params
          );

          const { code, message } = body;
          if (code === 0) {
            this.$Message.success(this.$t('m.errorCode' + code));
            setTimeout(() => {   
              this.$refs[name].resetFields();
              this.getCompanyBankList();
              this.creationType = true;
              this.editModal = false;                 
            }, 500);
          } else {
            this.$Message.error(message);
          }

        } else {
          this.loading = false;
          setTimeout(() => {
            this.loading = true;
          }, 0)
        }
      });
    },
    async deleteCompanyBank() {
      const { id } = this.row;
      const { body } = await this.$http.post(
        "/api/laocai/sysPayConfig/companyBankcard/info",
        {
          status: 2,
          id
        }
      );
      this.getCompanyBankList();
    },
    //获取全局配置项
    getConfigList() {
      this.configLoading = true;
      this.$http.get("/api/laocai/sys/config/list").then(
        response => {
          var list = response.body.result;
          this.configData = list;
          this.configLoading = false;
        },
        error => {
          console.log(error);
        }
      );
    },
    // switch事件
    handleSwitch(key, value, field) {
      let param = {
        key: key,
        value: value ? 1 : 0
      };
      if (field) {
        param.field = field;
      }

      this.$http.post("/helsinki/admin/config/update", param).then(
        ({ data: { errcode, info, data } }) => {
          if (errcode == 0) {
            this.$Message.success(info);
            this.getConfigList();
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    // 点击提价按钮
    handleSubmit(key, value, field) {
      let param = {
        key: key,
        value: value
      };
      if (field) {
        param.field = field;
      }
      this.$Modal.confirm({
        title: this.$t("m.tijiaoSub"),
        loading: true,
        closable: true,
        onOk: () => {
          this.$http.post("/helsinki/admin/config/update", param).then(
            ({ data: { errcode, info, data } }) => {
              if (errcode == 0) {
                this.$Message.success(info);
                this.getConfigList();
              }
              this.$Modal.remove();
            },
            error => {
              console.log(error);
            }
          );
        }
      });
    }
  }
};
</script>

<style lang="scss" scope>
.config-wrapper {
  width: 100%;
  height: 100%;
}

.systemConfig-wraaper {
  .title {
    padding: 30px 0 10px 15px;
    margin-bottom: 10px;
    .borderLeft {
      display: inline-block;
      width: 3px;
      height: 16px;
      background: #2d8cf0;
      margin-right: 10px;
      vertical-align: middle;
    }
    span {
      vertical-align: middle;
      font-size: 16px;
      color: #222222;
    }
  }
}

.icon-alert-style {
  margin-top: -2px;
  margin-left: 10px;
  margin-right: 2px;
  font-size: 14px;
  color: #2d8cf0;
}

.config-list {
  .config-item {
    display: flex;
    align-items: center;
  }
  .config-label {
    margin-right: 10px;
  }
  .config-control {
    width: 360px;
  }
}

.addUserBtn {
  margin: 15px 0;
}

.tabItem {
  padding: 10px 0;
  label {
    display: inline-block;
    margin-right: 10px;
    width: 100px;
  }
}
</style>
